<template>
  <div class="my-counter">
    <button
      type="button"
      class="btn btn-light"
      :disabled="obj.goods_count === 1"
      @click="subFn">-</button>
    <input
      type="number"
      class="form-control inp"
      v-model.number.lazy="goodsCount">
    <button
      type="button"
      class="btn btn-light"
      @click="addFn">+</button>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
  props: {
    obj: Object, // 商品对象
    i: Number
  },
  watch: {
    obj: {
      deep: true,
      handler(){ // 拿到商品数量, 判断小于1, 强制修改成1
        if (this.obj.goods_count < 1) {
          this.obj.goods_count = 1
        }
      }
    }
  },
  computed: {
    goodsCount: {
      get(){
        return this.obj.goods_count
      },
      set(v){
        if(v <= 1) v = 1
        this.setGoodsItemCount({
          index: this.i,
          count: v
        })
      }
    }
  },
  methods: {
    ...mapMutations('cart', ['decrease', 'increase', 'setGoodsItemCount']),
    subFn(){
      this.decrease(this.i)
    },
    addFn(){
      this.increase(this.i)
    }
  }
}
</script>

<style lang="less" scoped>
.my-counter {
  display: flex;
  .inp {
    width: 45px;
    text-align: center;
    margin: 0 10px;
  }
  .btn, .inp{
    transform: scale(0.9);
  }
}
</style>